/*
 * @Date: 2020-09-11 14:37:47
 * @LastEditors: 小枫
 * @LastEditTime: 2020-09-25 19:52:03
 * @FilePath: \feng-blog\app\controller\Article.ts
 */
import { Controller } from 'egg';

export default class ArticleController extends Controller {
  public async index() {
    const { ctx } = this;
    const { page, limit } = ctx.request.query;
    const nLimit = limit ? parseInt(limit) : 10;
    const nPage = page ? parseInt(page) * nLimit : 0;
    try {
      const result = await ctx.service.article.getArticlelist(nPage, nLimit);
      ctx.status = 200;
      ctx.body = {
        msg: '',
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: '',
        data: error,
      };
    }
  }

  public async create() {
    const { ctx } = this;
    const { title, content, tid } = ctx.request.body;
    try {
      const result = await ctx.service.article.createArticle(ctx.authUser, title, content, tid);
      ctx.body = {
        status: 200,
        msg: result,
      };
    } catch (error) {
      // console.log(error);
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async show() {
    const { ctx } = this;
    const { aid } = ctx.params;
    try {
      ctx.validate({ aid: 'number' }, ctx.params);
      const showResult = await ctx.service.article.getArticleDetail(aid);
      ctx.body = {
        stauts: 200,
        data: showResult,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async tag() {
    const { ctx } = this;
    const { tid } = ctx.params;
    const { page, limit } = ctx.request.query;
    const nLimit = limit ? parseInt(limit) : 10;
    const nPage = page ? parseInt(page) * nLimit : 0;
    try {
      const result = await ctx.service.article.getArticleByTag(tid, nPage, nLimit);
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async destroy() {
    const { ctx } = this;
    const { aid } = ctx.params;
    try {
      const result = await ctx.service.article.deleteArticleById(aid);
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }
}
